﻿using B.MESUI.Login.A_Public.Constants;
using B.MESUI.Login.A_Public.Helpers;
using B.MESUI.Login.A_Public.Model;
using B.MESUI.Login.ProdManagement.DTO;
using B.MESUI.Login.ProdManagement.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace B.MESUI.Login.ProdManagement.Services
{
    /// <summary>
    /// 工单管理服务类，封装了工单的增删查等相关业务逻辑。
    /// </summary>
    public static class WorkOrderService
    {
        /// <summary>
        /// 添加工单。
        /// </summary>
        /// <param name="request">工单添加请求对象</param>
        /// <returns>操作是否成功</returns>
        public static async Task<bool> AddWorkOrderAsync(AddWorkOrderRequest request)
        {
            try
            {
                var url = HttpClientHelper.GetWorkOrderUrl(ApiEndpoints.WorkOrder.AddWorkOrder);
                var response = await HttpClientHelper.PostAsync(url, request);
                var result = JsonConvert.DeserializeObject<ApiResponse<object>>(response);
                return result?.Success ?? false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取工单列表。
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="codeId">工单编码（可选）</param>
        /// <returns>分页的工单数据</returns>
        public static async Task<PagedResponse<WorkOrderListItem>> GetWorkOrderListAsync(int pageIndex = 1, int pageSize = 10, string codeId = null)
        {
            try
            {
                var url = HttpClientHelper.GetWorkOrderUrl(ApiEndpoints.WorkOrder.GetWorkOrderList);
                var parameters = new Dictionary<string, object>
                {
                    { "PageIndex", pageIndex },
                    { "PageSize", pageSize }
                };

                if (!string.IsNullOrEmpty(codeId))
                {
                    parameters.Add("CODEID", codeId);
                }

                var queryString = HttpClientHelper.BuildQueryString(parameters);
                if (!string.IsNullOrEmpty(queryString))
                {
                    url += $"?{queryString}";
                }

                var response = await HttpClientHelper.GetAsync(url);
                return JsonConvert.DeserializeObject<PagedResponse<WorkOrderListItem>>(response);
            }
            catch
            {
                return new PagedResponse<WorkOrderListItem> { pageDatas = new List<WorkOrderListItem>() };
            }
        }

        /// <summary>
        /// 删除工单。
        /// </summary>
        /// <param name="workOrderIds">要删除的工单ID列表</param>
        /// <returns>操作是否成功</returns>
        public static async Task<bool> DeleteWorkOrdersAsync(List<string> workOrderIds)
        {
            try
            {
                var url = HttpClientHelper.GetWorkOrderUrl(ApiEndpoints.WorkOrder.DeleteWorkOrder);
                var request = new DeleteWorkOrderRequest { WORKORDERIDS = workOrderIds };
                var response = await HttpClientHelper.PutAsync(url, request);
                var result = JsonConvert.DeserializeObject<ApiResponse<object>>(response);
                return result?.Success ?? false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取工单实体。
        /// </summary>
        /// <param name="codeId">工单编码</param>
        /// <param name="workOrderType">工单类型</param>
        /// <returns>工单实体对象</returns>
        public static async Task<WorkOrderListItem> GetWorkOrderEntityAsync(string codeId, string workOrderType)
        {
            try
            {
                var url = HttpClientHelper.GetWorkOrderUrl(ApiEndpoints.WorkOrder.GetWorkOrderEntity);
                var parameters = new Dictionary<string, object>
                {
                    { "CODEID", codeId },
                    { "WORKORDER_TYPE", workOrderType }
                };

                var queryString = HttpClientHelper.BuildQueryString(parameters);
                url += $"?{queryString}";

                var response = await HttpClientHelper.GetAsync(url);
                var result = JsonConvert.DeserializeObject<ApiResponse<WorkOrderListItem>>(response);
                return result?.resultData;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 获取甘特图数据。
        /// </summary>
        /// <param name="startDate">开始日期（可选）</param>
        /// <param name="endDate">结束日期（可选）</param>
        /// <param name="productionLine">产线（可选）</param>
        /// <returns>甘特图任务列表</returns>
        public static async Task<List<GanttTask>> GetGanttDataAsync()
        {
            // 1. 构造请求
            using (var client = new HttpClient())
            {
                // 2. 替换为你的实际API地址
                string url = "http://39.103.49.30:9983/api/WorkOrder/GetWorkOrderList";
                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                // 3. 读取响应内容
                var json = await response.Content.ReadAsStringAsync();

                // 4. 反序列化为 PagedResponse<WorkOrder>
                var result = JsonConvert.DeserializeObject<PagedResponse<WorkOrderListItem>>(json);

                // 5. 判空
                if (result?.pageDatas == null || result.pageDatas.Count == 0)
                    return new List<GanttTask>();

                // 6. WorkOrder -> GanttTask 映射
                var ganttTasks = result.pageDatas.Select((wo, idx) => new GanttTask
                {
                    Id = idx + 1,
                    codeid = wo.codeid,
                    starT_TIME = wo.starT_TIME,
                    enD_TIME = wo.enD_TIME,
                    numbeR_COL = wo.numbeR_COL,
                    workordeR_DESC = wo.workordeR_DESC,
                    productioN_LINE = wo.productioN_LINE
                }).ToList();

                return ganttTasks;
            }

        }
    }
}